package com.daguchuangyi.erp_android.productlist.imagetell;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioGroup;

import com.daguchuangyi.erp_android.R;
import com.daguchuangyi.erp_android.base.CompatStatusBarActivity;
import com.daguchuangyi.erp_android.model.LocalMediaWrapper;
import com.jude.utils.JUtils;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.theartofdev.edmodo.cropper.CropImageView;

import java.io.File;
import java.util.List;

public class ImageCropActivity extends CompatStatusBarActivity implements GalleryPenddingAdapter.OnLocalMediaCheckListener {
    private static final String TAG = "ImageCropActivity";

    public static final String KEY_URLS = "KEY_URIS";

    public static final String TAG_CROP_RESULTS = "TAG_CROP_RESULTS";
    public static final String TAG_CROP_TYPE = "TAG_CROP_TYPE";

    private RecyclerView mPenddingRv;

    private CropImageView mCropImageView;
    private GalleryPenddingAdapter mAdapter;

    private LocalMedia mCurrentCutLm;

//    private TextView mCutTv;

    private LocalMediaWrapper mLocalMediaWrapper = new LocalMediaWrapper();
    private RadioGroup mCropTypeRg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_crop);

        setImmersiveStatusBar(false, Color.parseColor("#000000"));

//        mCutTv = (TextView) findViewById(R.id.cut_tv);
        mCropTypeRg = (RadioGroup) findViewById(R.id.crop_type_rg);

        findViewById(R.id.cancel_tv).setOnClickListener(v -> {
            finish();
        });

        findViewById(R.id.done_tv).setOnClickListener(v -> {
            try {
                String ext = ".jpg";
                String path = ImageCropActivity.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString()
                        + File.pathSeparator + "cut" + File.pathSeparator;
                File file = new File(path);
                boolean makeDirResult = file.mkdirs();
                JUtils.Log("makeDirResult is : " + makeDirResult);
                float[] cropPoint = mCropImageView.getCropPoints();
                mLocalMediaWrapper.setCutPoint(cropPoint);
                for (int i = 0; i < cropPoint.length; i++) {
                    JUtils.Log(TAG, i + ":" + cropPoint[i]);
                }
                Uri outputUri = Uri.fromFile(File.createTempFile("cropped", ext, file));
                mCropImageView.saveCroppedImageAsync(outputUri);

            } catch (Exception e) {
//                throw new RuntimeException("Failed to create temp file for output image", e);
                JUtils.ToastLong("剪裁失败，请检查应用权限");
                e.printStackTrace();
            }
        });

        mCropImageView = (CropImageView) findViewById(R.id.crop_image_view);
        mCropImageView.setMinCropResultSize(50, 50);
        mCropImageView.setCropShape(CropImageView.CropShape.RECTANGLE);
        mCropImageView.setScaleType(CropImageView.ScaleType.CENTER_CROP);
        mCropImageView.setGuidelines(CropImageView.Guidelines.ON);
        mCropImageView.setShowProgressBar(true);

        mPenddingRv = (RecyclerView) findViewById(R.id.grallery_pendding_rv);
        mPenddingRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));

        List<LocalMedia> uriList = getIntent().getParcelableArrayListExtra(KEY_URLS);

        if (uriList == null || uriList.size() == 0) {
            throw new IllegalArgumentException("Please set uris for crop activity");
        }

        LocalMedia firstItem = uriList.get(0);
        mCurrentCutLm = firstItem;
        mCropImageView.setImageUriAsync(Uri.fromFile(new File(firstItem.getPath())));

        mCropImageView.setOnCropImageCompleteListener((view, result) -> {
            String cutPath = PictureFileUtils.getPath(ImageCropActivity.this, result.getUri());
            JUtils.Log("cutPath is : " + cutPath);
            mCurrentCutLm.setCutPath(cutPath);
            mCropImageView.setImageUriAsync(Uri.fromFile(new File(cutPath)));

            if (mPenddingRv.isShown()) {
                mAdapter.notifyDataSetChanged();
            }
            mLocalMediaWrapper.setLocalMedia(mCurrentCutLm);

            boolean isTotalRecognize = mCropTypeRg.getCheckedRadioButtonId() == R.id.crop_total_recognize;
            Intent intent = new Intent();
            intent.putExtra(TAG_CROP_RESULTS, mLocalMediaWrapper);
            intent.putExtra(TAG_CROP_TYPE, isTotalRecognize);
            setResult(Activity.RESULT_OK, intent);
            finish();
        });

        /*
        mCutTv.setOnClickListener(view -> {
            try {
                String ext = ".jpg";
                String path = ImageCropActivity.this.getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString()
                        + File.pathSeparator + "cut" + File.pathSeparator;
                File file = new File(path);
                file.mkdirs();
                Uri outputUri = Uri.fromFile(File.createTempFile("cropped", ext, file));
                mCropImageView.saveCroppedImageAsync(outputUri);
            } catch (IOException e) {
                throw new RuntimeException("Failed to create temp file for output image", e);
            }
        });
        */

        if (uriList.size() == 1) {
            mPenddingRv.setVisibility(View.GONE);
        } else {
            mAdapter = new GalleryPenddingAdapter(uriList);
            mAdapter.setOnLocalMediaCheckListener(this);
            DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL);
            dividerItemDecoration.setDrawable(ContextCompat.getDrawable(this, R.drawable.divider_gallery_pendding));
            mPenddingRv.addItemDecoration(dividerItemDecoration);
            mPenddingRv.setAdapter(mAdapter);
        }

    }

    @Override
    public void onPictureCheck(LocalMedia localMedia) {
        mCurrentCutLm = localMedia;
        String imgPath = TextUtils.isEmpty(mCurrentCutLm.getCutPath()) ? mCurrentCutLm.getPath() : mCurrentCutLm.getCutPath();
        mCropImageView.setImageUriAsync(Uri.fromFile(new File(imgPath)));
    }
}
